package org.an.proj.contacts.ui.msg;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.widget.MsgView;
import java.util.ArrayList;
import org.an.ku.base.BaseFragment;
import org.an.ku.util.DensityUtil;
import org.an.ku.util.ToastUtil;
import org.an.proj.contacts.MyApplication;
import org.an.proj.contacts.R;
import org.an.proj.contacts.config.LogUtil;
import org.an.proj.contacts.ui.contact.ContactDetailActivity;
import org.an.proj.contacts.util.IntentUtil;

/**
 * 创建时间：2016年10月13日14:48 <br>
 * 作者：fuchaoyang <br>
 * 描述：消息Fragment
 */
public class MsgFragment extends BaseFragment {
  public static final String TAG = "MsgFragment";
  private SegmentTabLayout mTabLayout;
  private ViewPager mViewPager;
  private String[] mTitle;
  private ArrayList<Fragment> mFragmentList;

  public MsgFragment() {
    // Required empty public constructor
  }

  public static MsgFragment newInstance() {
    MsgFragment fragment = new MsgFragment();
    //Bundle args = new Bundle();
    //fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 初始化数据放到这里
    mTitle = getContext().getResources().getStringArray(R.array.msg_tab_list);
    mFragmentList = new ArrayList<>();
    mFragmentList.add(new ChatMsgFragment());
    mFragmentList.add(new PhoneFragment());
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_msg, container, false);
    view.findViewById(R.id.iv_header).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        IntentUtil.goToOthers(mContext, ContactDetailActivity.class);
      }
    });
    mTabLayout = (SegmentTabLayout) view.findViewById(R.id.tab_layout);
    mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
    mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
      @Override public void onPageSelected(int position) {
        mTabLayout.setCurrentTab(position);
      }
    });

    mViewPager.setAdapter(new MyPagerAdapter(getFragmentManager()));

    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        //ToastUtil.toast(getActivity(), "onTabSelect:" + mTitle[position]);
        mViewPager.setCurrentItem(position, true);
      }

      @Override public void onTabReselect(int position) {
        ToastUtil.toast(getActivity(), "onTabReselect:" + mTitle[position]);
      }
    });
    mTabLayout.setIndicatorAnimDuration(300L);
    //mTabLayout.setCurrentTab();
    // 可也直接绑定Fragment，也可以不绑定在onTabSelect中处理ViewPager
    // fixme 这里修改了源码，第二个参数改为FragmentManager，因为Fragment嵌套Fragment时，需要getChildFragmentManager
    //mTabLayout.setTabData(mTitle, getChildFragmentManager(), R.id.fl_fragment, mFragmentList);
    mTabLayout.setTabData(mTitle);

    mTabLayout.showDot(1);
    mTabLayout.showMsg(0, 3);
    mTabLayout.setIndicatorMargin(1, 1, 1, 1);
    // 控件为固定高度:参照点为tab内容的右上角
    mTabLayout.setMsgMargin(0, 5, 5);
    MsgView msgView = mTabLayout.getMsgView(0);
    if (msgView != null) {
      msgView.getLayoutParams().width = DensityUtil.dip2px(MyApplication.getInstance(), 15);
      msgView.getLayoutParams().height = DensityUtil.dip2px(MyApplication.getInstance(), 15);
    }

    MsgView msgView1 = mTabLayout.getMsgView(1);
    if (msgView1 != null) {
      msgView1.setBackgroundColor(Color.parseColor("#6D8FB0"));
    }
    return view;
  }

  /**
   * 当依附的ActivityonResume时，Fragment也会回调onResume，
   */
  @Override public void onResume() {
    super.onResume();
    // 子Fragment会在父Fragment回调onResume之前回调onHiddenChanged方法，且会回调两次，第二次的时候isResumed(false),isHidden(false),isVisible(true)
    // isResumed(true),isHidden(false),isVisible(true),isAdded(true)
    LogUtil.i(TAG,
        String.format("onResume:isResumed(%b),isHidden(%b),isVisible(%b),isAdded(%b)", isResumed(),
            isHidden(), isVisible(), isAdded()));
  }

  @Override public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    LogUtil.i(TAG,
        String.format("onHiddenChanged:isResumed(%b),isHidden(%b),isVisible(%b),isAdded(%b)",
            isResumed(), isHidden(), isVisible(), isAdded()));
    // 第一次初始化的时候不会回调，从该tab切到其他tab（该Fragment被hide了）时回调，但是子Fragment不会回调
    // onHiddenChanged:isResumed(true),isHidden(true),isVisible(false),isAdded(true)

    // fixme 由于该方法只会在hide,show的时候回调，导致切换父fragment tab时，子Fragment不会回调此方法，如果需要子Fragment也回调，就手动调用
    for (int i = 0; i < mFragmentList.size(); i++) {
      Fragment fragment = mFragmentList.get(i);
      fragment.onHiddenChanged(fragment.isHidden());
    }
  }

  class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
      super(fm);
    }

    @Override public int getCount() {
      return mFragmentList.size();
    }

    @Override public Fragment getItem(int position) {
      return mFragmentList.get(position);
    }
  }
}
